import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model

from utils.myjwt import myjwt

User = get_user_model()

class MyAuthentication(BaseAuthentication):
    def authenticate(self,request):
        token=request.META.get("HTTP_AUTHORIZATION","")
        if not token:
            raise AuthenticationFailed("请先登录")
        tokendata=token.split(" ")[-1]
        try:
            dicdata=myjwt.check_token(tokendata)
            userid=dicdata.get("userid")
            info=User.objects.get(id=userid)
            return (info,tokendata)
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed("token过期")
        except jwt.InvalidTokenError:
            raise AuthenticationFailed("token错误")